#将8个文件合并为1个
import struct
import os

def isFloat(fnum):
    if fnum[0] == '-':
        return True
    if fnum[0] >= '0' and fnum[0] <= '9':
        return True
    return False

def mergeFile():
    f_bin = open('merge.dat','wb')
    dataFile = ['gpw_v4_population_count_rev11_2020_30_sec_1.asc',
            'gpw_v4_population_count_rev11_2020_30_sec_2.asc',
            'gpw_v4_population_count_rev11_2020_30_sec_3.asc',
            'gpw_v4_population_count_rev11_2020_30_sec_4.asc',
            'gpw_v4_population_count_rev11_2020_30_sec_5.asc',
            'gpw_v4_population_count_rev11_2020_30_sec_6.asc',
            'gpw_v4_population_count_rev11_2020_30_sec_7.asc',
            'gpw_v4_population_count_rev11_2020_30_sec_8.asc'
            ]
    #获取当前路径
    curPath = os.getcwd()
    for index in range(len(dataFile)):
        print(f'merge {dataFile[index]}')
        #待访问文件名字
        curFileName = dataFile[index]
        #合成读取待读取文件路径
        readPath = curPath + '\\gpw-v4-population-count-rev11_2020_30_sec_asc\\' + curFileName
        #读取
        f_txt = open(readPath,'r')
        #获取前六行概览信息 删除
        linencols = f_txt.readline()
        linenrows = f_txt.readline()
        linexllcorner = f_txt.readline()
        lineyllcorner = f_txt.readline()
        linecellsize = f_txt.readline()
        lineNODATA_value = f_txt.readline()
        print(f'{linencols}{linenrows}{linexllcorner}{lineyllcorner}{linecellsize}{lineNODATA_value}')
        #转换开始
        fcount = 0
        line = f_txt.readline()
        while line:
            f_num_list = line.split(' ')
            #转换文本文件为二进制文件
            for fnum in f_num_list:
                if isFloat(fnum):
                    #转换数据为二进制
                    # print(f'fnum:{fnum} fnum[0]:{fnum[0]} len:{len(fnum)}')
                    bin_num = struct.pack('>f',float(fnum))
                    f_bin.write(bin_num)
                    fcount = fcount+1
            line = f_txt.readline()
        #关闭文件
        f_txt.close()
        print(f'写入:{fcount}个数字')
    f_bin.close()